var express = require('express');
var router = express.Router();

var md5 = require("md5");
var fs=require("fs");
var conn= require('../conn');

router.use(function (req, res, next) {
  if(req.session.islogin==true){
  	 next();
 	}else{
  		res.redirect("/login");
 	}
 
 });

/* GET home page. */
router.get('/MemberCenter', function(req, res, next) {
	var  islogin;
    if(req.session.islogin==true){
        islogin = "<li><a href='/member/MemberCenter'>欢迎"+req.session.username+"</a></li><li><a href='/loginOut'>退出</a>&nbsp;<b>|</b>&nbsp;<a href='/member/myOrder'>订单查询</a></li>"
    }else{
        islogin  = '<li><a href="/login">你好，请登录</a></li> <li><a href="/register">注册</a></li>'
    }
  res.render('MemberCenter', { title: '会员中心',users:req.session.username,shopping_num:req.session.shopping_num,islogin:islogin});
});

router.get('/myOrder', function(req, res, next) {
	var sql='select * from order_infro where user_id='+req.session.user_id;
	conn.query(sql,function(err, rows, fields){
		var islogin;
		if(req.session.islogin==true){
        islogin = "<li><a href='/member/MemberCenter'>欢迎"+req.session.username+"</a></li><li><a href='/loginOut'>退出</a>&nbsp;<b>|</b>&nbsp;<a href='/member/myOrder'>订单查询</a></li>"
    }else{
        islogin  = '<li><a href="/login">你好，请登录</a></li> <li><a href="/register">注册</a></li>'
    }
	 res.render('myOrder', { title: '我的订单',myorder:rows,shopping_num:req.session.shopping_num,islogin:islogin});
	})
})
router.get('/changePassword', function(req, res, next) {
	var islogin;
	if(req.session.islogin==true){
        islogin = "<li><a href='/member/MemberCenter'>欢迎"+req.session.username+"</a></li><li><a href='/loginOut'>退出</a>&nbsp;<b>|</b>&nbsp;<a href='/member/myOrder'>订单查询</a></li>"
    }else{
        islogin  = '<li><a href="/login">你好，请登录</a></li> <li><a href="/register">注册</a></li>'
    }
	res.render("changePassword",{ title:'修改密码',shopping_num:req.session.shopping_num,islogin:islogin});
});


router.post('/dochangePassword',function(req, res, next){
	req.body.olderPassword=md5(req.body.olderPassword);
	req.body.newPassword=md5(req.body.newPassword);
	req.body.password_again=md5(req.body.password_again);
	if(req.body.olderPassword==req.session.password) {
			if(req.body.newPassword==req.body.password_again) {
				var sql = 'update users set password="'+req.body.newPassword+'" where id='+req.session.user_id;
					console.log(sql);
			      conn.query(sql,function(err, rows, fields){
			      	
					res.send("修改成功！");
				})
			}else{
				res.send("您再次输入的密码不正确")
			}
	}else{
			res.send("您输入的旧密码不正确")
		}
   
 })

router.get('/delOrder', function(req, res, next) {
  conn.query('delete from order_infro where id='+req.query.id, function(err, rows, fields){

  res.redirect("myOrder");

  })
});


module.exports = router;
